<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/31
 * Time: 14:33
 */

namespace osc\mobile\controller;

use osc\admin\controller\EndRemind;
use think\Db;
use think\Session;
use think\Loader;
use think\File;
use think\Request;
use osc\mobile\model\Member;

class Contract extends MobileBase
{

    /**
     * 验证是否登录
     */
    protected function _initialize()
    {

        parent::_initialize();
        define('UID',is_login());

        if (!Session::has("username")) {

            $this->redirect('login/login');

        }



    }

    /**验证二级密码
     * @return array|mixed
     */
    public function index(){
        session('warn','warn');

        $passwd2 = session("passwd2");
        $mobile = session("username");

        $user = Db::name('member')->where('username',$mobile)->find();
        $exch = Db::name('exchange_trade_acc')->where('username',$mobile)->find();
        
        if($passwd2)
        {
            $this->redirect('Contract/info');
        }

        if(request()->isPost()){
            $data=input('post.');

            $pwd2 = think_ucenter_encrypt($data['pwd2'],config('PWD_KEY'));

            if($pwd2!=$user['2password'])
            {
                return array('error'=>'二级密码输入有误');
            }else
            {
                //var_dump($rang_order[0]['state']);
                session('passwd2','passwd2');
                return array('success'=>'验证成功');
            }
            //var_dump($rang_order[0]['state']);	         //判断该用户当前执行的轮次，第一轮

            //var_dump($data);
            //$this->assign('userinfo',Db::name('member')->where('username',$mobile)->find());
            //return array('success'=>'修改密码成功','url'=>'/mobile')

        }

        $this->assign('top_title','二次密码验证');
        $this->assign('SEO',['title'=>'二次密码验证-'.config('SITE_TITLE')]);

        $this->assign('flag','user');

        return $this->fetch();
    }

    /**
     * 风险协议书
     * @return mixed
     */
    public function warn()
    {
        $warn = session("warn");

        $username = session("username");
        $exch = Db::name('exchange_trade_acc')->where('username',$username)->find();

        if(!$exch)
        {
            $this->error('请先完善交易所账户信息信息','user/exchange_trade');
        }

        /*$user_info = Db::name('member')->where('username',$username)->find();
//		print_r($user_info);exit;
        if($user_info['blacklist'] == 0){
            $this->error('您已被拉黑，不能进入理财','user/index');
        }*/

        $data = $this->request->param();

        if(isset($data['value'])){
            $this->redirect('Contract/programme');
        }
        //警示用户信息
        $this->assign('top_title','服务条款确认');
        $this->assign('SEO',['title'=>'服务条款确认-'.config('SITE_TITLE')]);

        return $this->fetch();

    }

    /**
     *  合约列表
     * @return mixed
     */
    public function info(){

        $username = session('username');

        

        $programme = Db::name('programme')->where('username',$username)->where('state<>3')->where('abn_state<>1')->order('id desc')->find();
//        print_r($delivery);exit;

        $free = Db::name('free_contract')->where('username',$username)->where('state<>5')->order('id desc')->find();

        $this->assign('free',$free);
        $this->assign('programme',$programme);
        $this->assign('top_title','奖励活动');
        return $this->fetch();
    }

    /**
     * 提货赠送方案收益
     * @return mixed
     */
    public function profit(){

        $username = session('username');
        $user = Db::name('member')->where('username',$username)->field('bao,jilt,jilin_bean')->find();
        $this->assign('user',$user);
        $this->assign('top_title','收益');
        return $this->fetch();
    }

    /**
     * 提货赠送方案申请
     * @return array|mixed
     */
    public function programme(){


        //查询当天申请条数
        $count = Db::name('programme')->where("sub_date = '".date('Y-m-d',time())."'")->count();

        //获取限制名额数
        $config = Db::name('config')->where('name','PICK_UP_QUOTA')->find();

        if($this->request->isPost()){
            $data = $this->request->param();

            if($count >= $config['value']){
                return ['error'=>'当天名额已申请完，请明天再来'];
            }
            $programme = Db::name('programme')->where('username',$data['username'])->where('state<2')->where('abn_state<>1')->count();


            if($programme > 0) return ['error'=>'您还有申请未审核'];

            if($data['num']<2000)
            {
                return ['error'=>'最小提货金额为2000'];
            }

            if($data['num']>200000)
            {
                return ['error'=>'最大提货金额为200000！'];
            }

            $token = Db::name('token')->where('token',$data['token'])->find();

            if($token){
                $this->error('请勿重复提交');
            }
            Db::name('token')->insert(['token'=>$data['token']]);

            unset($data['token']);
            unset($data['/mobile/Contract/programme']);

            $data['sub_date'] = date('Y-m-d',time());

            $res = Db::name('programme')->insert($data);

            if($res){
                return ['success'=>'申请成功'];
            }else{
                return ['error'=>'申请失败'];
            }
        }
        $username = session('username');
        //查询交易所
        $exchange = Db::name('exchange_house')->where('state',1)->select();

        $variety = Db::name('exchage_variety')->where('state',1)->select();
        $list = Db::name('programme')->where('username',$username)->order('id desc')->paginate(5,false, [
            'query' => Request::instance()->param(),//不丢失已存在的url参数
        ]);

        $page=$list->render(); //获取分页

        $this->assign('list',$list);
        $this->assign('page',$page);
        $this->assign('count',$count);
        $this->assign('exchange',$exchange);
        $this->assign('variety',$variety);
        $this->assign('username',$username);
        $this->assign('top_title','提货');
        return $this->fetch();
    }

    /**
     * 提货赠送方案凭证上传
     * @return mixed
     */
    public function programme_img(){

        if($this->request->isPost()){
            $data = $this->request->param();

            $files = request()->file('image');
            if(!$data || !$files){
                $this->error('没有内容，不能提交~');
            }

            //重复提交
            $token = Db::name('token')->where('token',$data['__token__'])->find();
            if($token){
                $this->error('请勿重复提交');
            }

            $programme = Db::name('programme')->where('id',$data['id'])->find();

            if($programme['abn_state'] != 2){
                $map['vou_date'] = date('Y-m-d',time());
            }

            //修改订单状态
            $map['state'] = 2;
            $map['abn_state'] = 0;

            $noe = Db::name('programme')->where('id',$data['id'])->update($map);

            //提货凭证上传
            $img = $this->doUpload($files,'programme_img','del_id',$data['id'],1);

//            print_r($img);exit;
            if($img['code'] == 1 && $noe){
                Db::name('token')->insert(['token'=>$data['__token__']]);
                $this->success('上传成功');
            }else{
                $this->error('上传失败');
            }
        }

        $get_data = $this->request->param();
        $info = Db::name('programme')->where('id',$get_data['id'])->find();

        $img = Db::name('programme_img')->where(['del_id'=>$info['id'],'seq_id'=>1])->select();
        $this->assign('info',$info);
        $this->assign('img',$img);
        $this->assign('top_title','提货凭证上传');
        return $this->fetch();
    }

    /**宝豆
     * @return mixed
     */
    public function bao(){
        $username = session('username');
        if(!$username)
        {
            $this->redirect('login/login');
        }

        $start = input('param.start');
        $end = input('param.end');

        if($start && $end){
            $map = [
                'username' => $username,
                "FROM_UNIXTIME(create_time,'%Y-%m-%d')" => array(['>',strtotime($start)],['<',strtotime($end)])
            ];
        }
        $map['username'] = $username;
        $map['type'] = 1;

        $list = Db::name('release')
            ->where($map)
            ->order('create_time desc')
            ->paginate(5,false, [
                'query' => Request::instance()->param(),//不丢失已存在的url参数
            ]);

        $page=$list->render(); //获取分页

        $user_info=Db::name('member')->where(array('username'=>$username))->find();

        $release = Db::name('release')->where(['username'=>$username,"FROM_UNIXTIME(create_time,'%Y-%m-%d')"=>date('Y-m-d',time()),'type'=>1])->find();

        $this->assign('user_info',$user_info);
        $this->assign('release',$release);
        $this->assign('start',$start);
        $this->assign('end',$end);
        $this->assign('list',$list);
        $this->assign('page',$page);
        $this->assign('empty',"<span style='margin-left:20px;'>没有数据</span>");

        $this->assign('top_title','我的宝豆');
        $this->assign('SEO',['title'=>'我的宝豆-'.config('SITE_TITLE')]);

        return $this->fetch();
    }

    /**
     * 宝豆签到释放处理
     * @return array
     */
    public function sign_in()
    {
        if($this->request->isAjax())
        {
            $data = $this->request->param();
            $username = session('username');
            //查询是否重复提交
            $token = Db::name('token')->where('token',$data['token'])->find();

            if($token){
                return ['error'=>'请勿重复提交'];
            }

            //查询当天是否申请过
            $release = Db::name('release')->where(['username'=>$username,"FROM_UNIXTIME(create_time,'%Y-%m-%d')"=>date('Y-m-d',time()),'type'=>1])->find();
            if($release){
                return ['error'=>'抱歉，您当天已申请过'];
            }

            //查询用户信息
            $user = Db::name('member')->where('username',$username)->find();

            if($user['bao'] == 0){
                return ['error'=>'抱歉，您的余额不足'];
            }

            //获取释放利率后的金额
            $release = get_release_rate($user['bao']);

            //设置释放记录
            $map = [
                'username'      => $username,
                'rate'          => $release['rate'],
                'num'           => $release['num'],
                'type'          => 1,
                'create_time'   => time()
            ];

            // 开启事务
            Db::startTrans();
            try{
                //扣除宝豆增加吉豆录入释放记录
                Db::name('member')->where('username',$username)->setInc('jilt',$map['num']);
                Db::name('member')->where('username',$username)->setDec('bao',$map['num']);

                Db::name('release')->insert($map);

                Db::name('token')->insert(['token'=>$data['token']]);

                // 更新成功 提交事务
                Db::commit();

                return ['success'=>'签到成功'];

            }catch (\Exception $e){
                // 更新失败 回滚事务
                Db::rollback();

                return ['error'=>'签到失败'];
            }
        }
    }



    /**吉豆
     * @return mixed
     */
    public function jilt(){
        $username = session('username');
        if(!$username)
        {
            $this->redirect('login/login');
        }

        $start = input('param.start');
        $end = input('param.end');

        if($start && $end){
            $map = [
                'username' => $username,
                "FROM_UNIXTIME(create_time,'%Y-%m-%d')" => array(['>',strtotime($start)],['<',strtotime($end)])
            ];
        }
        $map['username'] = $username;
        $map['type'] = 2;

        $list = Db::name('release')
            ->where($map)
            ->order('create_time desc')
            ->paginate(5,false, [
                'query' => Request::instance()->param(),//不丢失已存在的url参数
            ]);

        $page=$list->render(); //获取分页

        $user_info=Db::name('member')->where(array('username'=>$username))->find();

        $release = Db::name('release')->where(['username'=>$username,"FROM_UNIXTIME(create_time,'%Y-%m-%d')"=>date('Y-m-d',time())])->find();

        $this->assign('user_info',$user_info);
        $this->assign('release',$release);
        $this->assign('start',$start);
        $this->assign('end',$end);
        $this->assign('list',$list);
        $this->assign('page',$page);
        $this->assign('empty',"<span style='margin-left:20px;'>没有数据</span>");

        $this->assign('top_title','我的吉豆');
        $this->assign('SEO',['title'=>'我的吉豆-'.config('SITE_TITLE')]);

        return $this->fetch();
    }


    /**
     * 元宝
     * @return mixed
     */
    public function jilin_bean(){

        $username = session('username');
        if(!$username)
        {
            $this->redirect('login/login');
        }

        $user_info=Db::name('member')->where(array('username'=>$username))->find();
        $user_info['predeposit'] = (int)$user_info['predeposit'];
        $this->assign('user_info',$user_info);

        $this->assign('top_title','我的元宝');
        $this->assign('SEO',['title'=>'我的元宝-'.config('SITE_TITLE')]);

        return $this->fetch();
    }


    /**
     * 元宝兑换
     * @return array|mixed
     */
    public function change()
    {
        $username = session('username');

        if(request()->isPost()){

            $data=input('post.');

            $time = date('Hi',time());
            
            /*if($time > 930 && $time < 1530){
                return ['error'=>'不在申请时间段，请于每日9:30之前，或15:30之后进行申请'];
            }*/
            //进行数据判断
            if($data['variety_id']=="")
            {
                return array('error'=>'请选择交易品种');
            }

            if($data['number']=="")
            {
                return array('error'=>'请输入转换数量');
            }

            if(!(floor($data['number'])==$data['number']))
            {
                return array('error'=>'请输入正确的数量!');
            }

            if($data['number']<1)
            {
                return array('error'=>'请输入正确的数量');
            }

            $pwd2 = think_ucenter_encrypt($data['pwd2'],config('PWD_KEY'));
            $user=Db::name('member')->where('username',$username)->find();
            if($pwd2!=$user['2password'])
            {
                return array('error'=>'二级密码输入有误');
            }

            //判断是否有还没有结束的
            $res = Db::name('jilin_ticket')->where('username',$username)->where('state',0)->find();
            if($res)
            {
                return array('error'=>'您上一次申请还没有处理完毕!');
            }

            //查询收盘价
            $var=Db::name('value_config')->where('variety_id',$data['variety_id'])->order('dt desc')->find();

            //查询发行价
            $issue = Db::name('contract_issue')->where('variety_id',$data['variety_id'])->find();


            $sum = ceil(($var['rate'] -$issue['issue'])*$data['number']);

            if($sum > $user['jilin_bean'])
            {
                $num = floor($user['jilin_bean']/($var['rate'] -$issue['issue']));

                $error = '元宝不够，最大换购数为：'.$num;
                return array('error'=> $error,'url'=>'/mobile');
            }
            $map = [
                'token'		=> $data['token'],
                'username'	=> $username,
                'exchange_id'	=> $data['exchange_id'],
                'variety_id'	=> $data['variety_id'],
                'issue'			=> $var['rate'],
                'money'			=> $sum,
                'num'			=> $data['number'],
                'create_time'		=> time(),
            ];

            //存储兑换记录
            $res = Db::name('jilin_ticket')->insert($map);

            $member = new Member();

            //减少用户元宝数
            $red = $member->where('username',$username)->setDec('jilin_bean',$map['money']);

            if(!$res || !$red){
                if($res){
                    Db::name('jilin_ticket')->where('id',$res)->delete();
                }
                if($red){
                    $member->where('username',$username)->setInc('jilin_bean',$map['money']);
                }
                return array('error'=>'申请兑换失败','url'=>'/mobile');
            }
            return array('success'=>'申请兑换成功','url'=>'/mobile');
        }

        $start = input('param.start');
        $end = input('param.end');
        if($start && $end){
            $map = [
                'username' => $username,
                'create_time' => array(['>',strtotime($start)],['<',strtotime($end)])
            ];
        }
        $map['username'] = $username;
        $list = Db::name('jilin_ticket')
            ->where($map)
            ->order('create_time desc')
            ->paginate(10,false, [
                'query' => Request::instance()->param(),//不丢失已存在的url参数
            ]);

        $page=$list->render(); //获取分页
        $exchange = Db::name('exchange_house')->where('id','3')->select();
        $variety = Db::name('exchage_variety')->select();
//		print_r($variety);exit;
        $this->assign('start',$start);
        $this->assign('end',$end);
        $this->assign('list',$list);
        $this->assign('page',$page);
        $this->assign('exchange',$exchange);
        $this->assign('variety',$variety);
        $this->assign('top_title','元宝兑换');
        return $this->fetch();
    }


    /**
     * 用户元宝转让
     * @return array|mixed
     */
    public function jilin_turn()
    {
        $user = session('username');

        if(request()->isPost()){

            $data=input('post.');
            $data['token']  = input('post.__token__/s', null);

            if(is_int($data['num']))
            {
                return array('error'=>'转让数量必须输入整数!');
            }

            if($data['num'] <= 0)
            {
                return array('error'=>'转让金额必须大于0!');
            }

            if($data['num']%10  != 0 ){
                return array('error'=>'请输入10的整数倍!');
            }

            return $r=osc_service('common','Member')->jilin_usertf($data);

        }

        $list = Db::name('jilin_usertf')->where("username = $user or mobile = $user")->order('dt desc')->limit(50)->select();

        $this->assign('list',$list);
        $this->assign('user',$user);
        $this->assign('top_title','元宝转让');
        $this->assign('SEO',array('title'=>'元宝转让-'.config('SITE_TITLE')));
        return $this->fetch();

    }

    /**
     * 获取用户真实姓名
     * @return array
     */
    function getUserinfo()
    {
        if(request()->isPost()){

            $data=input('post.');

            if($data['mobile'])
            {
                $ret = Db::name('member')->where('username',$data['mobile'])->find();

                $dt['nickname'] = $ret['nickname'];
                $dt['username'] = $ret['username'];
                $dt['idcardname'] = $ret['idcardname'];

                return array($dt['idcardname']);

            }

        }
    }


    /**
     * 查询昨日收盘价以及认购价
     * @return array
     */
    public function yesterday(){
        if($this->request->isPost()){

            $param = $this->request->param();

            if(!$param){
                return array('code'=>0,'msg'=>'数据提交失败');
            }

            //查询收盘价
            $var=Db::name('value_config')->where('variety_id',$param['variety_id'])->order('dt desc')->find();

            if(!$var){
                return array('code'=>0,'msg'=>'获取失败,请联系客服');
            }

            //查询发行价
            $issue = Db::name('contract_issue')->where('variety_id',$param['variety_id'])->find();

            if(!$issue){
                return array('code'=>0,'msg'=>'获取失败,请联系客服');
            }

            $user=Db::name('member')->where('username',session('username'))->find();

            if(!$user){
                return array('code'=>0,'msg'=>'获取失败,请联系客服');
            }

            $data = [
                'rate'          => $var['rate'],
                'issue'          => $issue['issue'],
                'jilin_bean'    => $user['jilin_bean'],
                'jie'           => $var['rate']-$issue['issue'],
                'yu'           => floor($user['jilin_bean']/($var['rate']-$issue['issue'])),
            ];

            return array('code'=>1,'msg'=>'OK','data'=>$data);
        }

    }


    /**
     * 查询昨日收盘价以及认购价
     * @return array
     */
    public function can_yesterday(){
        if($this->request->isPost()){

            $param = $this->request->param();

            if(!$param){
                return array('code'=>0,'msg'=>'数据提交失败');
            }

            //查询收盘价
            $var=Db::name('value_config')->where('variety_id',$param['variety_id'])->order('dt desc')->find();

            if(!$var){
                return array('code'=>0,'msg'=>'获取失败,请联系客服');
            }

            //查询发行价
            $issue = Db::name('contract_issue')->where('variety_id',$param['variety_id'])->find();

            if(!$issue){
                return array('code'=>0,'msg'=>'获取失败,请联系客服');
            }

            $user=Db::name('member')->where('username',session('username'))->find();

            if(!$user){
                return array('code'=>0,'msg'=>'获取失败,请联系客服');
            }

            $data = [
                'rate'          => $var['rate'],
                'issue'         => $issue['issue'],
                'can_quota'     => $user['can_quota'],
                'jie'           => $var['rate']-$issue['issue'],
                'yu'            => floor($user['can_quota']/($var['rate']-$issue['issue'])),
            ];

            return array('code'=>1,'msg'=>'OK','data'=>$data);
        }

    }

    /**
     * 删除订单图片
     * @return array
     */
    public function delImg(){
        if($this->request->isAjax()){
            $param = $this->request->param();

            $img = Db::name($param['model'])->delete($param['id']);
            if($img){
                return ['code'=>1,'msg'=>'删除成功'];
            }else{
                return ['code'=>0,'msg'=>'删除失败'];
            }
        }else{
            return ['code'=>0,'msg'=>'请求失败，请重新尝试！'];
        }
    }


    /**
     * 判断合约是否进入审核
     * @param $contract_id
     * @param $type
     * @return int|string
     */
    function is_examine($contract_id,$type){
        if($type == 1){
            $mobile = 'contract_b1';
        }else{
            $mobile = 'contract_b2';
        }

        $res = Db::name($mobile)->where('id',$contract_id)->where("state>0 and state <4")->count();

        return $res;
    }


    /**
     * 阿拉伯数字转中文大写金额
     * @param $num
     * @param bool|true $mode
     * @param bool|true $sim
     * @return string
     */
    function NumToCNMoney($num,$mode = true,$sim = true){
        if(!is_numeric($num)) return '含有非数字非小数点字符！';
        $char  = $sim ? array('零','一','二','三','四','五','六','七','八','九')
            : array('零','壹','贰','叁','肆','伍','陆','柒','捌','玖');
        $unit  = $sim ? array('','十','百','千','','万','亿','兆')
            : array('','拾','佰','仟','','萬','億','兆');
        $retval = $mode ? '元':'点';
        //小数部分
        if(strpos($num, '.')){
            list($num,$dec) = explode('.', $num);
            $dec = strval(round($dec,2));
            if($mode){
                $retval .= "{$char[$dec['0']]}角{$char[$dec['1']]}分";
            }else{
                for($i = 0,$c = strlen($dec);$i < $c;$i++) {
                    $retval .= $char[$dec[$i]];
                }
            }
        }
        //整数部分
        $str = $mode ? strrev(intval($num)) : strrev($num);
        for($i = 0,$c = strlen($str);$i < $c;$i++) {
            $out[$i] = $char[$str[$i]];
            if($mode){
                $out[$i] .= $str[$i] != '0'? $unit[$i%4] : '';
                if($i>1 and $str[$i]+$str[$i-1] == 0){
                    $out[$i] = '';
                }
                if($i%4 == 0){
                    $out[$i] .= $unit[4+floor($i/4)];
                }
            }
        }
        $retval = join('',array_reverse($out)) . $retval;
        return $retval;
        /*echo ($this->NumToCNMoney(2.55)."<br>");
        echo ($this->NumToCNMoney(2.55,1,0)."<br>");
        echo ($this->NumToCNMoney(7965)."<br>");
        echo ($this->NumToCNMoney(7965,1,0)."<br>");
        echo ($this->NumToCNMoney(155555555.68)."<br>");
        echo ($this->NumToCNMoney(155555555.68,1,0)."<br>");
        echo ($this->NumToCNMoney(0.8888888)."<br>");
        echo ($this->NumToCNMoney(0.8888888,1,0)."<br>");
        echo ($this->NumToCNMoney(99999999999)."<br>");
        echo ($this->NumToCNMoney(99999999999,1,0)."<br>");*/
    }

    /**
     * 图片上传
     * @param $files    array       图片文件
     * @param $model    string      入库表名称
     * @param $id_name  int         关联字段名称
     * @param $id_value int         关联字段值
     * @param $seq_id   int         图片上传类型
     * @return int|string   array   返回值
     */
    function doUpload($files,$model,$id_name,$id_value,$seq_id){
        $info="";
        $map = null;
        foreach($files as $key=>$picFile){
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $picFile
                ->move(ROOT_PATH.'/public/uploads/images');
            /*获取存储路径，以便插入数据库*/
            $map[$key]['img_path']= "/public/uploads/images/".$info->getSaveName();
            $map[$key]['file_name'] = $info->getFilename();
            $map[$key][$id_name]  = $id_value;
            $map[$key]['seq_id']  = $seq_id;
        }
        $img = Db::name($model)->insertAll($map);

        if($info!=="" && $img){
            return ['code'=>1,'msg'=>$img];
        }else{
            // 上传失败获取错误信息
            return ['code'=>0,'msg'=>$files->getError()];
        }
    }

    /**
     * base_64码图片上传
     * @param $base_64
     * @param $contract_id      int       合约id
     * @param $apply_type       int       合约类型
     * @return int|mixed|string
     */
    function base64_img($base_64,$contract_id,$apply_type)
    {
        $type = 'png';//图片格式
        $pattern = '/data:.*base64,/U';
        $res = preg_replace($pattern, '', $base_64);
        $str = base64_decode($res);

        $url = '/public/uploads/picture/' . date('Ymd', time()) . '/';
        $PATH = ROOT_PATH . 'public/uploads/picture/' . date('Ymd', time()) . '/';
        if (!is_dir($PATH)) {
            mkdir($PATH, 0777, true);
        }//判断目录是否存在，不存在则创建
        $name = md5(rand(100, 999) . time());
        $imgPath = $PATH . $name . '.' . $type;

        file_put_contents($imgPath, $str);
        $data = [
            'img_path'      => $url . $name . '.' . $type,
            'file_name'     => $name . '.' . $type,
            'contract_id'   => $contract_id,
            'type'          => $apply_type,
            'date'          => time(),
        ];
        $id = Db::name('contract_autograph_img')->insertGetId($data);
        return $id;
    }


    /*+++++++++++++++++++++++++++++++++++++++
      +++++++++++++++新自由型合约+++++++++++++
      +++++++++++++++++++++++++++++++++++++++*/

    /**
     * 合约申请
     * @return mixed
     */
    public function free_apply(){
        $username = session('username');

        $user = Db::name('member')->where("username=$username")->find();

        if($this->request->isPost()){
            $param = $this->request->param();

            if($param['money'] < 999 and $param['money'] > 200001){
                return ['code'=>0,'msg'=>'申请金额不能小于1000，并且不能大于200000'];
            }

            $token = Db::name('token')->where('token',$param['__token__'])->find();
            if($token){
                $this->error('请勿重复提交');
            }

            $map = [
                'username'  => $username,
                'money'     => $param['money'],
                'sub_date'  => date('Y-m-d',time())
            ];

            $red = '';

            if($param['integral'] == 1)
            {
                $price = $param['money']*0.2;

                if($user['predeposit'] < $price)
                {
                    return ['code'=>0,'msg'=>'您的余额不足'];
                }
                $map['price'] = $price;
                $map['type'] = 1;

                $red = Db::name('member')->where('username',$username)->setDec('predeposit',$price);
            }

            if($param['integral'] == 2)
            {
                $price = $param['money']*0.2;

                if($user['jilin_bean'] < $price)
                {
                    return ['code'=>0,'msg'=>'您的余额不足'];
                }
                $map['price'] = $price;
                $map['type'] = 2;

                $red = Db::name('member')->where('username',$username)->setDec('jilin_bean',$price);
            }

            $res = Db::name('free_contract')->insert($map);

            if($res && $red){
                Db::name('token')->insert(['token'=>$param['__token__']]);
                return ['code'=>1,'msg'=>'申请成功'];
            }

            return ['code'=>0,'msg'=>'申请失败'];

        }
        //未提交凭证，禁止一个月申请合约
        $time = date('Y-m-d',time());

        $free_invalid = Db::name('free_contract')->where("username='".$username."' and b_state=0 and state<>5 and begin_day<'".$time."'")->order('begin_day desc')->find();

        if($free_invalid){
            if($time < date("Y-m-d",strtotime("+1 month",strtotime($free_invalid['begin_day'])))){
                $this->error('未达到合约申请条件');
            }
        }

        //一天内不可申请两次合约
        $free_state = Db::name('free_contract')->where('username',$username)->where('state > 0')->order('id desc')->find();

        if($free_state){

            //获取今天的日期
            $time = date("Y-m-d",time());

            $date=floor((strtotime($time)-strtotime($free_state['begin_day']))/86400);

            if($date == 0){
                $this->error('未达到在此申请条件');
            }
        }

        $free = Db::name('free_contract')->where("username=$username and state=0")->order('id desc')->find();

        $this->assign('free',$free);
        $this->assign('user',$user);
        $this->assign('top_title','合约申请');
        return $this->fetch();
    }

    /**
     * 新自由合约列表
     * @return mixed
     */
    public function free_list(){
        $username= session('username');

        $list = Db::name('free_contract')->where("username=$username and state<>5")->select();

        $this->assign('list',$list);
        $this->assign('top_title','合约列表');
        return $this->fetch();
    }

    /**
     * 合约详情
     * @return mixed
     */
    public function free_info(){
        $id = $this->request->param('id');
        if(!$id){
            $this->error('传输错误');
        }
        $info = Db::name('free_contract')->where("id=$id")->find();
        //获取合约周期
        if($info['state'] == 0){
            $this->error('您的合约还未分配');
        }
        $this->assign('info',$info);
        $this->assign('top_title','合约内容');
        return $this->fetch();
    }

    /**
     * 新自由合约买入凭证上传
     * @return mixed
     */
    public function free_buy(){
        if($this->request->isPost()){
            $data = $this->request->param();

            $files = request()->file('image');
            if(!$data || !$files){
                $this->error('没有内容，不能提交~');
            }

            $token = Db::name('token')->where('token',$data['__token__'])->find();

            if($token){
                $this->error('请勿重复提交');
            }

            //判断是否超过时限

            $free = Db::name('free_contract')->where('id',$data['id'])->find();

            $time = date("Y-m-d",time());
            $date=floor((strtotime($time)-strtotime($free['begin_day']))/86400);

            if($date > 0 ){
                $this->error('超出上传时限~');
            }

            //判断合约是否审核
            if($free['state'] > 1 and $free['state'] != 4)
            {
                $this->error('合约已进入审核，不可上传');
            }

            //修改订单状态
            if($free['state'] == 4){
                $map['state'] = 1;
            }
            $map['b_state'] = 1;


            $noe = Db::name('free_contract')->where('id',$data['id'])->update($map);

            //卖出凭证上传
            $img = $this->doUpload($files,'free_contract_img','free_id',$data['id'],1);

            if($img['code'] == 1 && $noe){
                Db::name('token')->insert(['token'=>$data['__token__']]);
                $this->success('上传成功');
            }else{
                $this->error('上传失败');
            }
        }

        $id = $this->request->param('id');

        $free = Db::name('free_contract')->where("id=$id")->find();

        $remark = Db::name('free_contract_remark')->where('free_id',$id)->where(['type'=>1])->find();

        $img = Db::name('free_contract_img')->where(['free_id'=>$id,'seq_id'=>1])->select();

        $this->assign('info',$free);
        $this->assign('img',$img);
        $this->assign('remark_one',$remark);
        $this->assign('top_title','买入凭证上传');
        return $this->fetch();
    }


    /**
     * 新自由合约卖出凭证上传
     * @return mixed
     */
    public function free_sell(){
        if($this->request->isPost()){
            $data = $this->request->param();

            $files = request()->file('image');
            if(!$data || !$files){
                $this->error('没有内容，不能提交~');
            }

            $token = Db::name('token')->where('token',$data['__token__'])->find();

            if($token){
                $this->error('请勿重复提交');
            }

            //判断是否超过时限

            $free = Db::name('free_contract')->where('id',$data['id'])->find();

            $time = date("Y-m-d",time());
            $date=floor((strtotime($time)-strtotime($free['end_day']))/86400);

            if($date > 3 ){
                $this->error('超出上传时限~');
            }

            //判断合约是否审核
            if($free['state'] > 1 and $free['state'] != 4){
                $this->error('合约已进入审核，不可上传');
            }

            //修改订单状态
            if($free['state'] == 4){
                $map['state'] = 1;
            }
            $map['s_state'] = 1;

            $noe = Db::name('free_contract')->where('id',$data['id'])->update($map);

            //卖出凭证上传
            $img = $this->doUpload($files,'free_contract_img','free_id',$data['id'],2);
            if($img['code'] == 1 && $noe){
                Db::name('token')->insert(['token'=>$data['__token__']]);
                $this->success('上传成功');
            }else{
                $this->error('上传失败');
            }
        }
        $id = $this->request->param('id');

        $free = Db::name('free_contract')->where("id=$id")->find();

//        print_r($free);exit;

        $remark = Db::name('free_contract_remark')->where('free_id',$id)->where(['type'=>2])->order('id desc')->find();

        $img = Db::name('free_contract_img')->where(['free_id'=>$id,'seq_id'=>2])->select();

        $this->assign('info',$free);
        $this->assign('img',$img);
        $this->assign('remark_one',$remark);
        $this->assign('top_title','卖出凭证上传');
        return $this->fetch();
    }

    /**
     * 提交申请审核
     * @return array
     */
    public function examine(){
        if($this->request->isPost()){
            $data = $this->request->param();
            $map['state'] = 2;
            $res = Db::name('free_contract')->where('id',$data['id'])->update($map);

            if($res){
                return ['success'=>'提交成功'];
            }else{
                return ['error'=>'提交失败'];
            }
        }
    }

}